package registerCenter.impl;

import registerCenter.ServiceRegistry;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultServiceRegistry implements ServiceRegistry {
    /**
     *服务名：service对象 所实现接口 的完整类名 -> service对象
     */
    private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();

    /**
     *用来保存已经注册的对象的类名
     */
    private static final Set<String> registeredService = ConcurrentHashMap.newKeySet();


    @Override
    public <T> void register(T service) {
        String serviceName = service.getClass().getCanonicalName();
        if (registeredService.contains(serviceName)) {
            return ;
        }

        //获取service对象所实现的接口，因为一个对象可以实现多个接口
        Class<?>[] interfaces = service.getClass().getInterfaces();
        if (interfaces.length == 0){
            return ;
        }

        registeredService.add(serviceName);
        for(Class<?> i : interfaces){
            serviceMap.put(i.getCanonicalName(), service);
        }
    }

    @Override
    public Object getService(String serviceName) {
        Object res = serviceMap.get(serviceName);
        if(res == null) {
            System.out.println("service NOT FOUND");
            return null;
        }
        return res;
    }
}
